import request from '@/utils/request'
import { RootThunkAction } from '..'
// 获取详情文章
export function getArticleDetail(id: string): RootThunkAction {
  return async (dispatch) => {
    const res = await request('/articles/' + id)
    dispatch({
      type: 'article/seveDatail',
      payload: res.data,
    })
  }
}

// 获取文章的评论
export function geyCommentList(id: string): RootThunkAction {
  return async (dispatch) => {
    const res = await request('/comments', {
      params: {
        type: 'a',
        source: id,
      },
    })
    dispatch({
      type: 'article/saveComment',
      payload: res.data,
    })
  }
}

// 获取文章的评论
export function getMoreCommentList(
  id: string,
  offset: string
): RootThunkAction {
  return async (dispatch) => {
    const res = await request('/comments', {
      params: {
        type: 'a',
        source: id,
        offset,
      },
    })
    dispatch({
      type: 'article/saveMoreComment',
      payload: res.data,
    })
  }
}

// 点赞
export function likeAritcle(id: string, attitude: number): RootThunkAction {
  return async (dispatch) => {
    if (attitude === 1) {
      await request.delete('/article/likings/' + id)
    } else {
      await request.post('/article/likings', { target: id })
    }
    await dispatch(getArticleDetail(id))
  }
}

// 收藏
export function colleckAritcle(
  id: string,
  is_collected: boolean
): RootThunkAction {
  return async (dispatch) => {
    if (is_collected) {
      await request.delete('/article/collections/' + id)
    } else {
      await request.post('/article/collections', { target: id })
    }
    await dispatch(getArticleDetail(id))
  }
}

// 关注
export function followUser(
  aut_id: string,
  is_followed: boolean
): RootThunkAction {
  return async (dispatch, getState) => {
    if (is_followed) {
      await request.delete('/user/followings/' + aut_id)
    } else {
      await request.post('/user/followings', { target: aut_id })
    }
    await dispatch(getArticleDetail(getState().article.detail.art_id))
  }
}
